<template>
  <!--给用户添加角色-->
  <div v-loading="loading">
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose"
    >
      <el-form :model="roleForm">
        <el-tree
            :data="roleData"
            show-checkbox
            ref="roleTree"
            :check-strictly=true
            :default-checked-keys="this.roleList"
            node-key="id"
            :default-expand-all=true
            :props="defaultProps">
        </el-tree>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitRoleHandle('roleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {getRoleListInfo} from "@/api/sys/role"
import {assignRole, getUserRoleByUserId} from "@/api/sys/user"

export default {
  name: "assignRole",
  data() {
    return {
      loading: false,
      dialogVisible: false,
      roleForm: {},
      //当前表单的userId
      userId: 0,
      roleData: [],
      defaultProps: {
        label: 'name'
      },
      // 树形控件默认选项
      roleList: [],
    }
  },
  methods: {
    openDialog(userId) {
      this.dialogVisible = true
      this.userId = userId
    },
    //关闭前的回调
    handleClose() {
      this.resetForm()
    },
    resetForm() {
      this.userId = 0
      this.roleForm = {}
      this.dialogVisible = false
    },
    submitRoleHandle() {
      const data = {
        roleIds: this.$refs.roleTree.getCheckedKeys(),
        userId: this.userId
      }
      assignRole(data).then(res => {
        this.resetForm()
        this.$emit("handle", res)
        this.$message({
          type: "success",
          message: "操作成功"
        })
      })
    },
    getRoleList() {
      getRoleListInfo().then(res => {
        this.roleData = res.data
      })
    },
    //获取当前表单的角色列表
    getUserRoleList(userId) {
      if (userId === 0) {
        return
      }
      this.loading = true
      getUserRoleByUserId(userId).then(res => {
        this.roleList = this.getRoleArrays(res.data)
        this.$nextTick(() => {
          if (this.roleList === undefined) {
            this.roleList = []
          }
          this.$refs.roleTree.setCheckedKeys(this.roleList)
        })
        this.loading = false
      })
    },
    getRoleArrays(arrays) {
      let roles = []
      for (let arr of arrays) {
        roles.push(arr.roleId)
      }
      return roles
    }
  },
  created() {
    this.getRoleList()
  },
  watch: {
    userId: function () {
      this.getUserRoleList(this.userId)
    },
  }
}
</script>

<style scoped>

</style>
